<?php

require_once 'jujucock.php';
require_once 'optparse.php';

define('PORT', 54344);

$opt_parser = new OptionParser();
$opt_parser->addOption('', '--noisy', 'noisy', 'show noisy information', 'bool');
$opt_parser->addOption('', '--times', 'times', 'times to ping-pong');
$opt_parser->addOption('', '--bytes', 'bytes', 'size of message to ping-pong');
try {
	list($options, $args) = $opt_parser->parse( $argv );
}
catch(Exception $ex) {
	echo 'Exception: ',$ex->getMessage(),"\n";
	exit(2);
}

$noisy = false;
if (isset($options['noisy'])) {
    $noisy = $options['noisy'];
}
if (isset($options['times'])) {
    $times = $options['times'];
}
else {
    $times = 10;
}
if ($times < 1) { 
    $times = 10;
}
if (isset($options['bytes'])) {
    $bytes = $options['bytes'];
}
else {
    $bytes = 0;
}
if ($bytes < 1) {
    $bytes = 0;
} 
$bytes_pad = str_repeat('A', $bytes);

///////////////////////////////////////////////////////////////////////

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$ok = socket_connect($sock, '127.0.0.1', PORT);
if (!$ok) {
    $errorstr = sprintf("Error Creating Socket -- [%d] %s", socket_last_error(), socket_strerror(socket_last_error()));
    printf("%s\n", $errorstr);
    socket_close($sock);
    exit(1);
}

$channel = new JuTCPChannel($sock);
$request = "Hello,World.";

$packet = new Packet();
$packet->setRequest();
$packet->service = 'ECHO';
$packet->body = join('', array($request, $bytes_pad));

$time_start = microtime(true);
for ($i=0; $i<$times; $i++) {
    list($record, $packid) = enpack($packet);
    $channel->send($record . "\n");
    if ($noisy) {
        printf("send #%d (packid:%d) %s\n", $i+1, $packid, $record);
    }
    $record = '';
    $length = $channel->recv($record);
    $pkt = depack($record);
    if ($noisy) {
        printf("recv #%d (packid:%d) %s\n", $i+1, $pkt->packid, $record);
    }
}
$time_stop = microtime(true);
$time_last = $time_stop - $time_start;
$tps = $times / $time_last;
$bw = $times * strlen($packet->body) * 2 / $time_last;
if ($bw > 1048576) {
    $bw = sprintf('%.2f MB/s', $bw / 1048576.0);
}
elseif ($bw > 1024) {
    $bw = sprintf('%.2f KB/s', $bw / 1024.0);
}
else {
    $bw = sprintf('%d B/s', $bw);
}

printf('times: %d, time-last: %.2f seconds, tps: %.2f, bw: %s%s', $times, $time_last, $tps, $bw, PHP_EOL);

sleep(1);

socket_close($sock); 